package com.wanfajie.smsdistribute.db.bean.template

import com.j256.ormlite.dao.Dao
import com.j256.ormlite.dao.ForeignCollection
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.field.ForeignCollectionField
import com.j256.ormlite.misc.BaseDaoEnabled
import com.j256.ormlite.table.DatabaseTable
import com.wanfajie.smsdistribute.db.helper.TemplateDatabaseHelper
import com.wanfajie.smsdistribute.template.convert.TemplateConvertable
import com.wanfajie.smsdistribute.template.convert.TemplateConverter

@DatabaseTable(tableName = "sd_sms_template")
data class TemplateBean(
        @DatabaseField(columnName = ID, generatedId = true)
        val id: Int = 0,

        @DatabaseField(columnName = TITLE)
        var title: String = "",

        @DatabaseField(columnName = CONTENT)
        var content: String = ""
): BaseDaoEnabled<TemplateBean, Int>(), TemplateConvertable {

    companion object {
        const val ID = "id"
        const val TITLE = "title"
        const val CONTENT = "content"
        const val CREATE_TS = "create_ts"
        const val UPDATE_TS = "update_ts"

        @JvmStatic
        private val DAO: Dao<TemplateBean, Int> = TemplateDatabaseHelper.getDao(TemplateBean::class.java)

        fun get(templateId: Int): TemplateBean? {
            return DAO.queryForId(templateId)
        }
    }

    init {
        setDao(DAO)
    }

    @ForeignCollectionField(eager = true)
    val placeholders: ForeignCollection<Placeholder> = dao.getEmptyForeignCollection("placeholders")

    @DatabaseField(columnName = CREATE_TS)
    val createTimestamp: Long = System.currentTimeMillis()

    @DatabaseField(columnName = UPDATE_TS)
    var updateTimestamp: Long = System.currentTimeMillis()

    fun addPlaceholder(start: Int, end: Int): Boolean {
        if (id == 0)
            throw IllegalStateException("实体未保存")

        val placeholder = Placeholder(this, start, end)
        return placeholders.add(placeholder)
    }

    fun addPlaceholder(point: Pair<Int, Int>) {
        addPlaceholder(point.first, point.second)
    }

    fun replacePlaceholder(points: List<Pair<Int, Int>>) {
        placeholders.clear()
        points.forEach {
            addPlaceholder(it)
        }
    }

    override fun <R> convert(converter: TemplateConverter<R>): R {
        converter.setRawMaterial(content)
        placeholders.forEach {
            val name = content.substring(it.startPos+1, it.stopPos)
            converter.mark(name, it.startPos to it.stopPos)
        }

        return converter.convert()
    }

    override fun update(): Int {
        updateTimestamp = System.currentTimeMillis()
        return super.update()
    }
}
